<template>
  <t-skeleton :loading="loading">
    <div style="margin-bottom: var(--td-comp-margin-s)">
      <t-button
        v-if="oneSee.result !== 2&&oneSee.result !==1"
        v-permission="['system:order-designer:save-design-info']"
        @click="
          handleOpenDialog('create', {
            orderId: orderDetails.id,
            logType: 'oneSee',
            otherFileUrl: [],
            remark: oneSee.remark,
          })
        "
      >
        上传一见
      </t-button>
    </div>
    <t-alert v-if="oneSee.remark" style="margin-bottom: var(--td-comp-margin-s)">
      <span>备注：{{ oneSee.remark }}</span>
      <span v-if="oneSee.result !== null" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(oneSee.result - 1).theme">{{
          getTagThemeAndLabel(oneSee.result - 1).label
        }}</t-tag>
      </span>
    </t-alert>
    <div class="content" v-if="oneSee.fileUrls.length>0">
      <t-space direction="vertical" style="width: 100%">
        <t-collapse expand-mutex @change="handlePanelChange">
          <t-collapse-panel
            v-for="(file, index) in oneSee.fileUrls"
            :key="index"
            :value="index.toString()"
            :header="getListItemMeta(index, file.createTime)"
          >
            <!-- <t-space direction="vertical" size="large" style="width: 100%"> -->
              <!-- <t-list :split="true">
                <t-list-item v-for="(file2, index2) in file.fileUrl" :key="index2">
                  <t-list-item-meta :image="file2.url" :title="file2.name" />
                  <template #action>
                    <t-button variant="text" shape="square" @click="downloadFile(file2.url)">
                      <download-icon />
                    </t-button>
                  </template>
                </t-list-item>
              </t-list> -->
              <div class="file-container">
                <template v-for="(file2, index) in file.fileUrl" :key="index">
                  <file-preview :file="file2" />
                </template>
              </div>
            <!-- </t-space> -->
          </t-collapse-panel>
        </t-collapse>
      </t-space>
    </div>
    <!-- 空 -->
    <t-empty v-if="!oneSee.remark" style="margin: 100px"></t-empty>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData }"
      :api-map="{ create: createDesignInfo }"
      header="上传一见"
      width="700px"
      :on-before-save-data="handleDialogSaveData"
      @request-success="handleDialogRequestSuccess"
    >
      <!-- 居中 -->
      <t-form-item label="方案文件">
        <upload2 v-model:files="formData.otherFileUrl" />
        <!-- <upload v-model:files="formData.otherFileUrl" /> -->
      </t-form-item>
      <t-form-item label="备注" name="remark" :rules="[{ required: true, message: '请输入备注' }]">
        <t-textarea v-model:value="formData.remark" placeholder="请输入备注" />
      </t-form-item>
    </custom-dialog>
  </t-skeleton>
  <!-- 粘性审批对话框 -->
  <sticky-approve-dialog ref="stickyApproveDialogRef7" :order-id="orderDetails.id" approve-type="7" />
  <sticky-approve-dialog ref="stickyApproveDialogRef13" :order-id="orderDetails.id" approve-type="13" />
  <!-- 发起人 -->
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog1Style"  ref="stickyInitApproveDialogRef7" :order-id="orderDetails.orderId || orderDetails.id" approve-type="7" />
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog2Style" ref="stickyInitApproveDialogRef13" :order-id="orderDetails.orderId || orderDetails.id" approve-type="13" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { DownloadIcon } from 'tdesign-icons-vue-next';
import { CollapseProps, MessagePlugin } from 'tdesign-vue-next';
import { computed, inject, onMounted, reactive, Ref, ref, useTemplateRef } from 'vue';

import { createDesignInfo, getDesignInfoList } from '@/api/order/details';
import CustomDialog from '@/components/custom/dialog/index.vue';
import Upload2 from '@/components/upload/index2.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import StickyInitApproveDialog from '@/pages/approve/components/sticky-init-approve-dialog.vue';
import FilePreview from '@/components/file-preview/index.vue';
// import { useDictionaryStore, useUserStore } from '@/store';

// 用户仓库
// const userStore = useUserStore();
// // 字典仓库
// const dictionaryStore = useDictionaryStore();
// 订单详情
const orderDetails = inject<Ref<Record<string, any>>>('orderDetails');
// 容器类名
// const containerClassName = window.document.getElementsByClassName('view-order-scroll').length
//   ? '.view-order-scroll'
//   : '.tdesign-starter-layout';
// 加载状态
const loading = ref(false);
// 方案信息列表
const oneSeeList = ref([]);
// 方案信息
const oneSee = reactive({
  remark: '',
  result: null,
  fileUrls: [],
});
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: any) => {
  const map = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};

// 下载文件
const downloadFile = (url: string) => {
  // 浏览器打开url
  window.open(url);
};
const getListItemMeta = (index: number, uploadTime: string) => {
  return `第${index + 1}上传,上传时间为${dayjs(uploadTime).format('YYYY-MM-DD HH:mm:ss')}`;
};
const handlePanelChange: CollapseProps['onChange'] = (val) => {
  console.log(val);
};
// 处理获取方案信息列表
const handleGetoneSeeList = () => {
  loading.value = true;
  const params = {
    orderId: orderDetails.value.id,
    logType: 'oneSee',
  };
  getDesignInfoList(params)
    .then((data) => {
      if (!data) return;
      oneSeeList.value = data.fileUrls;
      oneSee.remark = data.remark;
      oneSee.result = data.result;
      oneSee.fileUrls = data.fileUrls;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
onMounted(() => {
  handleGetoneSeeList();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  // 设置初始值

  customDialogRef.value.open(mode, params);
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  let isValid = true;
  let st = '';
    const hasWaitingFiles = params.otherFileUrl.some((item: any) => item.status === 'waiting');
  if (hasWaitingFiles) {
    MessagePlugin.warning('有文件待上传，请点击上传文件');
    return false;
  }
  params.otherFileUrl.forEach((item: any) => {
    if (item.type === '') {
      const fileType = item.url.split('.').pop();
      st += fileType;
    } else {
      st += item.type;
    }

    console.log(st);
  });
  console.log(st);
  // 所有图片格式
  if (st.indexOf('dwg') === -1) {
    MessagePlugin.warning('请上传dwg文件');
    isValid = false;
  }
  if (!isValid) {
    return false;
  }

  return params;
};
// 处理对话框请求成功
const handleDialogRequestSuccess = () => {
  handleGetoneSeeList();
};
interface DialogRef {
  visible: boolean;
  open: () => void;
  close: () => void;
}
// 粘性审批对话框ref
const stickyApproveDialogRef7 = useTemplateRef('stickyApproveDialogRef7');
const stickyApproveDialogRef13 = useTemplateRef('stickyApproveDialogRef13');
const stickyInitApproveDialogRef13 = ref<DialogRef | null>(null);
const stickyInitApproveDialogRef7 = ref<DialogRef | null>(null);

onMounted(() => {
  const { approveType } = orderDetails.value;
  if (approveType === '7')   stickyApproveDialogRef7.value.open();
  if (approveType === '13')  stickyApproveDialogRef13.value.open();
  stickyInitApproveDialogRef7.value.open();
  stickyInitApproveDialogRef13.value.open();
});
// 判断是否同时显示多个对话框
const isMultiple = computed<boolean>(() => {
  return stickyInitApproveDialogRef13.value?.visible && stickyInitApproveDialogRef7.value?.visible;
});

// 第一个对话框的样式
const dialog1Style = computed(() => {
  if (isMultiple.value) {
    return { left: '40%' }; // 多个对话框时，第一个对话框靠左
  }
  return {}; // 单个对话框时，样式不变
});

// 第二个对话框的样式
const dialog2Style = computed(() => {
  if (isMultiple.value) {
    return { left: '60%' }; // 多个对话框时，第二个对话框靠右
  }
  return {}; // 单个对话框时，样式不变
});

</script>

<style lang="less" scoped>
.content {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  .anchor {
    width: 150px;
    position: sticky;
    top: 100px;
  }

  .list {
    width: 100%;
  }
}
.file-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin: 12px 0;
}
</style>
